<template>
  <div class="important">
    <el-button @click="importDialog = true"></el-button>
    <el-dialog
      :title="deductionType == 1 ? '批量导入减款' : '批量导入充值'"
      :visible.sync="importDialog"
      width="1000px"
      center
      :close-on-click-modal="false"
      :before-close="closeDialogImport"
      :show-close="!importLoad"
    >
      <div class="grid-content bg-purple aa" v-if="importDialog">
        <div class="header_select">
          <!-- <div>
            <el-button type="primary" @click="thetemplate()" size="mini"
              >execl模板下载</el-button
            >
          </div> -->
          <div class="bulk_import">
            <el-upload
              class="upload-demo"
              action
              :on-change="handleChange"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              :file-list="fileListUpload"
              :limit="limitUpload"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :auto-upload="false"
            >
              <el-button type="primary" @click="handleclickto()" size="mini"
                >浏览文件</el-button
              >
            </el-upload>
          </div>
          <div class="packge_batch">
            <el-button
              type="primary"
              @click="packgebatchto(tableChecked)"
              size="mini"
              >导入数据</el-button
            >
          </div>
          <div class="packge_batch">
            <span>钱包号:</span>
            <el-select
              v-model="WalletNo"
              placeholder="请选择钱包号"
              size="mini"
              style="width:130px"
            >
              <el-option
                v-for="item in paylist"
                :key="item.walletNo"
                :label="item.walletName"
                :value="item.walletNo"
              ></el-option>
            </el-select>
          </div>
          <div class="packge_batch">
            <span>{{ deductionType == 1 ? "减款类型" : "充值类型" }}:</span>
            <el-select
              v-model="deductionTypeId"
              placeholder="请选择"
              size="mini"
              style="width:130px"
            >
              <el-option
                v-for="item in deductionlist"
                :key="item.pkTypeId"
                :label="item.typeName"
                :value="item.pkTypeId"
              ></el-option>
            </el-select>
          </div>
        </div>
        <el-table
          :data="changestudentlist"
          :stripe="true"
          style="width: 100%"
          border="border"
          :header-cell-style="headFirst"
          highlight-current-row
          @selection-change="handleSelectionChange"
          :show-overflow-tooltip="true"
          key="table1"
          v-loading="importLoad"
          ref="importTable"
          :cell-style="(res) => headFirst_col(res, [])"
        >
          <el-table-column
            label="是否选中"
            prop="isCheck"
            align="center"
            width="50px"
          >
            <template slot="header" slot-scope="scope">
              <el-checkbox
                :value="isSelectAll"
                @change="CheckSelectAll"
                :disabled="isError"
              />
            </template>
            <template slot-scope="scope">
              <el-checkbox
                :value="scope.row.isCheck"
                @change="(isCheck) => CheckSelect(isCheck, scope.row)"
                :disabled="isError"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="deductionType == 1 ? '减款情况' : '充值情况'"
            prop="content"
            v-if="isError"
          ></el-table-column>
          <el-table-column label="姓名" prop="userName"></el-table-column>
          <el-table-column label="卡号" prop="cardNumber"></el-table-column>
          <el-table-column
            :label="deductionType == 1 ? '减款金额(元)' : '充值金额(元)'"
            prop="rechargeAmount"
          ></el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChangeY"
          @current-change="handleCurrentChangepageY"
          :current-page="pageY"
          :page-sizes="[20, 40, 80, 120]"
          :page-size="pageSizeY"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalY"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      WalletNo: "",
      paylist: [],
      // 钱包号
      deductionTypeId: "",
      deductionlist: [],
      /**
       * 文件内容
       */
      fileListUpload: [],
      limitUpload: 1,
      // 是否全选
      isSelectAll: false,
      // 表格中拿出的原始数据
      changestudentY: [],
      // 原始页数
      pageY: 1,
      // 每条个数
      pageSizeY: 20,
      // 总条数
      totalY: 0,
      importDialog: false,
      // 渲染的表格数据
      changestudentlist: [],
      // 表格加载
      importLoad: false,
      // 是否显示错误原因
      isError: false,
      // 选中数据
      tableChecked: [],
    };
  },
  props: {
    /**
     * 1 减款 2充值
     */
    deductionType: {
      type: Number,
      default: 1,
    },
  },
  created() {
    this.unitGuid = this.$store.state.user.changeschoolid;
    // 获取钱包
    this.getPayNumber();
    // 获取无卡-备注类型
    this.getConType();
  },
  methods: {
    // 获取钱包
    getPayNumber() {
      this.paylist = [];
      this.platformWalletlist = [];
      this.$http({
        url: this.$http.adornUrl("/unit/unit-wallet-info-list"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.unitGuid,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          data.messageContent.map((item) => {
            if (Number(item.walletNo) != 100) {
              this.paylist.push(item);
            } else {
              this.platformWalletlist.push(item);
            }
          });
          if (this.paylist.length != 0) {
            this.WalletNo = this.paylist[0].walletNo;
          }
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: "error",
          });
        }
      });
    },
    // 获取无卡-备注类型
    getConType() {
      this.$http({
        url: this.$http.adornUrl(
          this.deductionType == 1
            ? "/unit/deduction-type-list"
            : "/unit/recharge-type-list"
        ),
        method: "post",
        data: this.$http.adornData({
          messageContent: this.unitGuid,
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.deductionlist = data.messageContent;
          if (this.deductionlist.length != 0) {
            this.deductionTypeId = this.deductionlist[0].pkTypeId;
          }
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: "error",
          });
        }
      });
    },
    //导入窗口关闭
    closeDialogImport() {
      this.changestudentlist = [];
      this.isError = false;
      this.importDialog = false;
    },
    // 用户导入显示,
    showImportDialog() {
      // 数据初始化
      this.initList();
      // // 钱包号制裁为空
      // this.WalletNo = "";
      // this.deductionTypeId = "";
      this.importDialog = true;
    },
    /**
     * 用户导入数据处理
     */
    // 数据初始化
    initList() {
      // 关闭加载
      this.importLoad = false;
      // 渲染表格初始化
      this.changestudentlist = [];
      // 表格中拿出的原始数据
      this.changestudentY = [];
      // 原始页数
      this.pageY = 1;
      // 每条个数
      this.pageSizeY = 20;
      // 总条数
      this.totalY = 0;
      // 原始的显示数据数
      this.showPageSizeY = 20;
      this.isSelectAll = false;
    },

    // 导入数据处理
    getData() {
      let arr = [];
      this.changestudentY.map((item) => {
        if (item.isCheck) {
          arr.push(item);
        }
      });
      return arr;
    },
    // 导入按钮功能
    packgebatchto() {
      if (this.WalletNo == "") {
        this.$message({
          showClose: true,
          message: "请选择钱包号，在进行导入",
          type: "warning",
        });
        return false;
      }
      if (this.deductionTypeId == "") {
        this.$message({
          showClose: true,
          message:
            "请选择" + this.deductionType == 1
              ? "减款类型"
              : "充值类型" + "，在进行导入",
          type: "warning",
        });
        return false;
      }

      if (this.importLoad) {
        this.$message({
          showClose: true,
          message: "正在批量导入请勿重复操作",
          type: "warning",
          duration: "500",
        });
        return false;
      }
      let tableCheckedto = this.getData();
      if (tableCheckedto[0] && tableCheckedto[0].errorStr) {
        this.$message({
          message: "数据非法",
          type: "warning",
        });
        return;
      }
      if (tableCheckedto.length == 0) {
        this.$message({
          message: "没有批量数据",
          type: "warning",
        });
        return false;
      }
      let messageContent = {
        dataList: tableCheckedto,
        unitGuid: this.unitGuid,
        deductionType: this.deductionTypeId,
        walletNo: this.WalletNo,
      };
      console.log(messageContent)
      this.$confirm(
        this.deductionType == 1 ? "确定批量导入减款?" : "确定批量导入充值?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.toList(tableCheckedto, messageContent);
        })
        .catch(() => {});
    },
    // 导入数据的接口
    toList(tableCheckedto, messageContent) {
      let timeOut = Math.ceil(tableCheckedto.length / 1000);
      this.$message({
        showClose: true,
        duration: 1000 * (2 + timeOut),
        message: "正在导入，请勿关闭窗口",
        type: "warning",
      });

      this.importLoad = true;
      this.$httpblob({
        url: this.$httpblob.adornUrl(
          this.deductionType == 1
            ? "/card/ready-money-deduction-excel"
            : "/card/ready-money-recharge-excel"
        ),
        method: "post",
        data: this.$httpblob.adornData({
          messageContent: messageContent,
          messageType: 0,
        }),
      }).then(({ data }) => {
        // 数据初始化
        this.initList();
        // console.log(data)
        if (data.messageCode == 500) {
          this.$message({
            message: data.errorMessage,
            type: "warning",
          });
        }
        if (data.messageCode == 200) {
          this.table1 = false;
          this.tablelist = data.messageContent;
          this.$message({
            message:
              this.deductionType == 1 ? "批量导入减款成功" : "批量导入充值成功",
            type: "success",
          });
          let arrto = data.messageContent;
          this.changestudentY = arrto;
          this.exportExcel();
          this.isError = false;
          this.importDialog = false;
          this.changestudentlist = [];
          //   if (data.messageContent.length != 0) {
          //     this.isError = true;
          //     // this.$message({
          //     //   showClose: true,
          //     //   duration: 1000 * 5,
          //     //   message: data.errorMessage,
          //     //   type: "warning",
          //     // });
          //     let arrto = data.messageContent;
          //     this.changestudentY = arrto;
          //     this.getUserList(this.pageY, this.pageSizeY);
          //     this.totalY = arrto.length;
          //     this.$nextTick(() => {
          //       this.$refs["importTable"].doLayout();
          //     });
          //   } else {
          //     this.isError = false;
          //     this.importDialog = false;
          //     this.changestudentlist = [];
          //     this.initpage();
          //   }
        }
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 导出结果
    exportExcel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        let multiHeader = [];
        let merges = [];
        const tHeader = [
          this.deductionType == 1 ? "减款情况" : "充值情况",
          "姓名",
          "卡号",
          this.deductionType == 1 ? "减款金额(元)" : "充值金额(元)",
        ];
        const filterValArr = [
          "content",
          "userName",
          "cardNumber",
          "rechargeAmount",
        ];

        const { export_json_to_excel } = require("../../excel/Export2Excel");
        const filterVal = filterValArr;
        const list = this.changestudentY;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader,
          header: tHeader,
          data,
          merges,
          filename:
            this.deductionType == 1
              ? "导入减款结果" + this.getimeto()
              : "导入充值结果" + this.getimeto(),
          tableheader: "1",
        });
      });
    },
    //导入表格选择变更
    handleSelectionChange(val) {
      console.log(val);
      this.tableChecked = val;
    },
    handleclickto() {},
    //导入函数
    importfxx(obj) {
      // 把错误号去除
      this.isError = false;
      // 数据初始化
      this.initList();
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((v) => {
            let obj = {};
            obj.userName = v["姓名"];
            obj.cardNumber = v["卡号"];
            console.log(this.deductionType)
            if (_this.deductionType == 1) {
              console.log(v["减款金额(元)"])
              obj.rechargeAmount = v["减款金额(元)"];
            } else {
              obj.rechargeAmount = v["充值金额(元)"];
            }
            arr.push(obj);
          });
          _this.studentlist = [...arr];
          console.log(arr)
          let arrto = JSON.parse(JSON.stringify(_this.studentlist));
          // _this.studentlist = arrto
          let list = [];

          if (arrto.length > 0) {
            // _this.changestudentlist = arrto;
            let is = 0;
            let indexId = 0;
            arrto.map((item, index) => {
              if (!item.userName || !item.cardNumber || !item.rechargeAmount) {
                delete arrto[index];
                is++;
              } else {
                item.isCheck = _this.isSelectAll;
                item.id = indexId;
                indexId ++;
                list.push(item);
              }
            });
            if (is) {
              _this.$message({
                message: `已预览${list.length}条数据，忽略了${is}条未填写必填字段的数据`,
                type: "warning",
              });
            }
          }
          console.log(arrto);
          console.log(list);
          _this.changestudentY = list;
          _this.getUserList(_this.pageY, _this.pageSizeY);
          _this.totalY = list.length;
        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    //导入excel相关
    handleRemove(file, fileList) {
      // 初始化
      this.initList();
      this.isError = false;
      this.changestudentlist = [];
      this.fileTemp = null;
    },
    //导入excel相关
    handleExceed(file, fileList) {
      fileList[0].name = file[0].name;
      this.fileTemps = file[0];
      if (this.fileTemps) {
        if (
          this.fileTemps.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemps.type == "application/vnd.ms-excel"
        ) {
          this.changestudentlist = [];
          this.table1 = true;
          this.importfxx(this.fileTemps);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //导入excel相关
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.changestudentlist = [];
          this.table1 = true;
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //时间转换
    getdata(date) {
      date = Math.round(date * 100000) / 100000;
      var Minustime = 1.33333 * 24 * 3600000;
      date = new Date(date * 24 * 3600000 - Minustime);
      date.setYear(date.getFullYear() - 70);
      return this.dateFormat("YYYY-mm-dd", date);
    },
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      // console.log(opt)
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },
    handleCurrentChangepageY(val) {
      this.pageY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.changestudentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      );
    },
    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val;
      console.log(this.changestudentY);
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val;
      this.changestudentY.map((item) => {
        item.isCheck = val;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.important {
  padding: 0 20px;
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  /deep/.site-wrapper .el-pagination {
    text-align: center;
  }
}
.bg-purple {
  /deep/.el-dialog__body {
    padding-top: 0px;
  }
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  height: 100%;
  .header_title {
    padding: 20px 0;
    font-weight: bolder;
    text-align: center;
    border-bottom: 1px solid #e5e9f2;
    color: #909399;
  }
  .el-table th {
    height: 100%;
    display: table-cell !important;
  }

  .header_select {
    height: 40px;
    // background-color: #F5F5F5;
    width: 98%;

    display: flex;
    align-items: center;
    .cardnumber,
    .username,
    .usernumber {
      display: flex;
      align-items: center;
      //   padding-left: 10px;
      width: 200px;
      div:nth-child(1) {
        width: 40px;
      }
    }
    .searchbutton {
      // height:36px;
      padding-left: 10px;
      display: flex;
      flex: 1;
      justify-content: space-between;
      .addstudent {
        padding-right: 20px;
      }
      .el-checkbox {
        // align-self: left;
        width: 150px;
        margin-top: 20px;
      }
    }
    .bulk_import {
      //   padding-left: 20px;
      .upload-demo {
        display: flex;
        align-items: center;
        /deep/.el-upload-list__item-name {
          margin-right: 22px;
        }
      }
    }
    .packge_batch {
      padding-left: 20px;
    }
  }
}
.grid-content.bg-purple.aa {
  padding: 0 20px;
}
</style>